﻿#include "SymbolsSrc.h"
#include "OptionManager.h"
#include "Tools.h"
#include "FileOperator.h"

SymbolsSrc::SymbolsSrc()
{
	std::string symbolDir = OptionManager::Instance().GetSymbolDir();
	time_t cuTime = Tools::GetCurrentTimeStamp();
	tm tmStruct = Tools::GetDateTimeFrmStamp(cuTime);
	std::string dateStr = Tools::DateToStr(tmStruct);
	symbolDir += dateStr;
	// 创建目录
	//Tools::CreateDir(symbolDir);
	m_symbolFileBin = symbolDir + ".symbols";
}

SymbolsSrc::~SymbolsSrc()
{
}

void SymbolsSrc::AppendSymbol(CThostFtdcInstrumentField *pInstrument)
{
	if (pInstrument == nullptr)
	{
		return;
	}
	m_sybolList.emplace_back(SymbolPackage::SymbolInfo());
	SymbolPackage::SymbolInfo &contract = m_sybolList.back();
	contract.ProductClass = pInstrument->ProductClass;
	strncpy(contract.InstrumentID, pInstrument->InstrumentID, strlen(pInstrument->InstrumentID));
	contract.InstrumentID[strlen(pInstrument->InstrumentID)] = 0;
	strncpy(contract.ExchangeID, pInstrument->ExchangeID, strlen(pInstrument->ExchangeID));
	contract.ExchangeID[strlen(pInstrument->ExchangeID)] = 0;
	strncpy(contract.InstrumentName, pInstrument->InstrumentName, strlen(pInstrument->InstrumentName));
	contract.InstrumentName[strlen(pInstrument->InstrumentName)] = 0;
	contract.VolumeMultiple = pInstrument->VolumeMultiple;
	contract.PriceTick = pInstrument->PriceTick;
	contract.LongMarginRatio = pInstrument->LongMarginRatio;
	contract.ShortMarginRatio = pInstrument->ShortMarginRatio;
	contract.MaxMarketOrderVolume = pInstrument->MaxMarketOrderVolume;
	contract.MinMarketOrderVolume = pInstrument->MinMarketOrderVolume;
	contract.MaxLimitOrderVolume = pInstrument->MaxLimitOrderVolume;
	contract.MinLimitOrderVolume = pInstrument->MinLimitOrderVolume;
	contract.DeliveryYear = pInstrument->DeliveryYear;
	contract.DeliveryMonth = pInstrument->DeliveryMonth;
}

void SymbolsSrc::SaveSymbols()
{
	// 保存二进制
	FileOperator::FileBin symbolFile(m_symbolFileBin.c_str(), "wb");
	if (symbolFile.FileInstance() != nullptr)
	{
		for (std::list<SymbolPackage::SymbolInfo>::iterator itSymbol = m_sybolList.begin(); itSymbol != m_sybolList.end(); ++itSymbol)
		{
			const SymbolPackage::SymbolInfo &tmpInfo = *itSymbol;
			fwrite(&tmpInfo, sizeof(SymbolPackage::SymbolInfo), 1, symbolFile.FileInstance());
		}
	}
}